﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Optimizer
{
    class Stupid : IOptimizer
    {
        public string Name()
        {
            return "Простий випадковий пошук";
        }

        double StepLen = 1; //длина шага
        double Kappa = 0.618;
        double Eps = 0.01; //точность
        int N = 20; //кол-во проб
        double F, FPr;
        Point XPr;

        Point X0 = new Point()
        {
            X1 = -1,
            X2 = 1,
        };

        private Random R = new Random();

        private double NextRandom()
        {
            return 2 * this.R.NextDouble() - 1;
        }

        private Point NextRandomPoint()
        {
            Point Temp = new Point()
            {
                X1 = NextRandom(),
                X2 = NextRandom(),
            };
            return Temp.Norm();
        }
        
        private Point DeltaX()
        {
            return StepLen * NextRandomPoint();
        }

        public Point Do(Func<Point, double> f)
        {
            F = f(X0);

            do
            {
                int PrNum = 0;
                while (PrNum < N)
                {
                    XPr = X0 + DeltaX();
                    FPr = f(XPr);
                    if (FPr < F)
                    {
                        X0 = XPr;
                        F = FPr;
                        PrNum = 0;
                        StepLen = StepLen / Kappa;
                    }
                    else PrNum++;
                }
                StepLen = StepLen * Kappa;
            } while (StepLen > Eps);
            return X0;
        }
    }
}